var group = {
    baseUrl: "/lrdrole",
    entity: "group",
    tableId: "groupTable",
    toolbarId: "toolbar",
    unique: "roleCd",
    currentItem: {},
    currentAuthorityMenu: {}
};
group.columns = function () {
    return [
        {
            field: 'selectItem',
            radio: true
        },{  
            title: '序号',
            formatter: function (value, row, index) {  
                return index+1;  
            }  
        }, {
            field: 'roleCd',
            title: '角色编码'
        }, {
            field: 'roleName',
            title: '角色名称'
        }, {
            field: 'desc',
            title: '角色说明'
        }, {
            field: 'orgName',
            title: '创建机构'
        },{
            field: 'roleFwC',
            title: '角色范围'
        }];
};
//得到查询的参数
group.queryParams = function (params) {
	if (!params)
        return {
			roleName:$("#roleName").val(),
			roleFw:$("#roleFw").val()
        };
    var temp = { //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
        limit: params.limit, //页面大小
        page: params.offset/params.limit+1, //页码
        roleName:$("#roleName").val(),
		roleFw:$("#roleFw").val()
    };
    return temp;
};
group.responseHandler = function(response){
	if(response.code =='200'){
		return response.data;
	}
	return false;
};
group.init = function () {
    group.table = $('#' + group.tableId).bootstrapTable({
        url: group.baseUrl, //请求后台的URL（*）
    	method: 'get', //请求方式（*）
    	toolbar: '#' + group.toolbarId, //工具按钮用哪个容器
    	cache: false, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true, //是否显示分页（*）
        pageNumber: 1, //初始化加载第一页，默认第一页
        pageSize: 10, //每页的记录行数（*）
        pageList: [10, 25, 50, 100], //可供选择的每页的行数（*）
        showColumns: false, //是否显示所有的列
        showRefresh: true, //是否显示刷新按钮
        clickToSelect: true, 
        sidePagination: "server", //分页方式：client客户端分页，server服务端分页（*）
        showToggle: true, //是否显示详细视图和列表视图的切换按钮
        singleSelect:true,
        striped:true,
        queryParams: group.queryParams,//传递参数（*）
        responseHandler:group.responseHandler,
        columns: group.columns()
    });
};
group.select = function (layerTips) {
    var rows = group.table.bootstrapTable('getSelections');
    if (rows.length == 1) {
        group.currentItem = rows[0];
        return true;
    } else {
        layerTips.msg("请选中一行");
        return false;
    }
};
group.refresh = function () {
    group.table.bootstrapTable('refresh', group.queryParams());
};


layui.use(['form', 'layedit', 'laydate', 'element'], function () {
    group.init();
    var editIndex;
    //var layerTips = parent.layer === undefined ? layui.layer : parent.layer, //获取父窗口的layer对象
    var layerTips = layui.layer;
        layer = layui.layer, //获取当前窗口的layer对象
        form = layui.form,
        layedit = layui.layedit,
        laydate = layui.laydate;
    var addBoxIndex = -1;  
    var json = {//(字典枚举)筛选
            "roleFw" : "SYS_ORG_YYFW",//角色范围
    };
    selectOnload({
        "json" : json,
        "isDefault" : false,
        "func":form.render,
        "length" : 1
    });
    function renderForm(){
    	  layui.use('form', function(){
    	   var form = layui.form;
    	   form.render();
    	  });
      }
    //初始化页面上面的按钮事件
    $('#btn_query').on('click', function () {
        group.table.bootstrapTable('refresh', group.queryParams());
    });
    $('#btn_add').on('click', function () {
        if (addBoxIndex !== -1)
            return;
        var rows = group.table.bootstrapTreeTable('getSelections');
        var id = "-1";
        if (rows.length == 1) {
            id = rows[0].id;
        }
        //本表单通过ajax加载 --以模板的形式，当然你也可以直接写在页面上读取
        $.get(group.entity + '/edit', null, function (form) {
            addBoxIndex = layer.open({
                type: 1,
                title: '添加角色',
                content: form,
                id:'lrd_role',
                btn: ['保存', '取消'],
                shade: [0.3, '#393D49'],
                shadeClose: true,
                offset: ['20px', '10%'],
                area: ['80%', '80%'],
                maxmin: true,
                yes: function (index) {
                    layedit.sync(editIndex);
                    //触发表单的提交事件
                    $('form.layui-form').find('button[lay-filter=edit]').click();
                },
                full: function (elem) {
                    var win = window.top === window.self ? window : parent.window;
                    $(win).on('resize', function () {
                        var $this = $(this);
                        elem.width($this.width()).height($this.height()).css({
                            top: 0,
                            left: 0
                        });
                        elem.children('div.layui-layer-content').height($this.height() - 95);
                    });
                },
                success: function (layero, index) {
                    var form = layui.form;
                   // editIndex = layedit.build('description_editor');
                    editIndex =layedit.build('description_editor',{
                    	 tool: [  'strong' //加粗
                 	          ,'italic' //斜体
                 	          ,'underline' //下划线
                 	          ,'del' //删除线
                 	          ,'|' //分割线
                 	          ,'left' //左对齐
                 	          ,'center' //居中对齐
                 	          ,'right' //右对齐
                 	       ]
                     });
                    form.render();
                    //查询selec 角色范围
                    $.get('/admin/dic/SYS_ORG_YYFW', null, function (data) {
                    	var flag = data.data;
                    	for(var i=0;i<flag.length;i++ ){
                    		$("#groupType").append("<option value="+flag[i].value+">"+flag[i].label+"</option>"); 
                    	}
                    	//重新渲染form
                    	renderForm();
                    });
                    
                    form.on('submit(edit)', function (data) {
                        $.ajax({
                            url: group.baseUrl+'/add',
                            type: 'post',
                            data: data.field,
                            dataType: "json",
                            success: function (data) {
                            	if(data.code=='200'){
	                                layerTips.msg('添加成功');
	                                layerTips.close(index);
	                                group.refresh();
                            	}else{
                            		layerTips.msg(data.message);
	                                layerTips.close(index);
                            	}
                            }

                        });
                        //这里可以写ajax方法提交表单
                        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                    });
                },
                end: function () {
                    addBoxIndex = -1;
                }
            });
        });
    });
    $('#btn_edit').on('click', function () {
        var rows = group.table.bootstrapTreeTable('getSelections');
        if (group.select(layerTips)) {
        	var result= group.currentItem;
            $.get(group.entity + '/edit', null, function (form) {
                layer.open({
                    type: 1,
                    title: '编辑角色',
                    id:'lrd_role',
                    content: form,
                    btn: ['保存', '取消'],
                    shade: [0.3, '#393D49'],
                    shadeClose: true,
                    offset: ['20px', '10%'],
                    area: ['80%', '80%'],
                    maxmin: true,
                    yes: function (index) {
                        layedit.sync(editIndex);
                        //触发表单的提交事件
                        $('form.layui-form').find('button[lay-filter=edit]').click();
                    },
                    full: function (elem) {
                        var win = window.top === window.self ? window : parent.window;
                        $(win).on('resize', function () {
                            var $this = $(this);
                            elem.width($this.width()).height($this.height()).css({
                                top: 0,
                                left: 0
                            });
                            elem.children('div.layui-layer-content').height($this.height() - 95);
                        });
                    },
                    success: function (layero, index) {
                        var form = layui.form;
                        setFromValues(layero, result);
                        layero.find('#description_editor').val(result.desc);
                        //editIndex = layedit.build('description_editor');
                        editIndex = layedit.build('description_editor',{
                           	tool: [  'strong' //加粗
                        	          ,'italic' //斜体
                        	          ,'underline' //下划线
                        	          ,'del' //删除线
                        	          ,'|' //分割线
                        	          ,'left' //左对齐
                        	          ,'center' //居中对齐
                        	          ,'right' //右对齐
                        	       ]
                            });
                        layero.find(":input[name='code']").attr("disabled", "");
                        $("#roleCd").attr("disabled",true);
                        //查询selec 角色范围
                        $.get('/admin/dic/SYS_ORG_YYFW', null, function (data) {
                        	var flag = data.data;
                        	for(var i=0;i<flag.length;i++ ){
                        		$("#groupType").append("<option value="+flag[i].value+">"+flag[i].label+"</option>"); 
                        	}
                        	$("#groupType").val(result.roleFw);
                        	//重新渲染form
                        	renderForm();
                        });
                        
                        form.render();

                        form.on('submit(edit)', function (data) {                     	
                            $.ajax({
                                url: group.baseUrl,
                                type: 'put',
                                data: data.field,
                                dataType: "json",
                                success: function (data) {
                                	if(data.code=='200'){
                                		layerTips.msg('更新成功');
	                                    layerTips.close(index);
	                                    group.refresh();
	                                }else {
	                                    layerTips.msg(data.message);
	                                    layerTips.close(index);
	                                }
                            	}

                            });
                            //这里可以写ajax方法提交表单
                            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                        });
                    }
                });
            });

        }
    });
    $('#btn_del').on('click', function () {
        if (group.select(layerTips)) {
        	
            var id = group.currentItem.roleCd;
            layer.confirm('确定删除数据吗？', null, function (index) {
                $.ajax({
                    url: group.baseUrl + "/" + id,
                    type: "DELETE",
                    success: function (data) {
                        if (data.code == '200') {
                            layerTips.msg("移除成功！");
                            location.reload();
                        } else {
                            layerTips.msg(data.message);
                            //location.reload();
                        }
                    }
                });
                layer.close(index);
            });
        }
    });
    //分配权限
    $('#btn_resourceManager').on("click", function () {
        if (group.select(layerTips)) {
            var id = group.currentItem.roleCd;
            var nodeMap = {};
            $.get(group.entity + '/authority', null, function (form) {
                var index = layer.open({
                    type: 1,
                    title: '分配权限',
                    content: form,
                    btn: ['保存', '取消'],
                    shade: false,
                    offset: ['20px', '20%'],
                    area: ['600px', '400px'],
                    maxmin: true,
                    yes: function (index) {
                        //触发表单的提交事件
                        $('form.layui-form').find('button[lay-filter=edit]').click();
                    },
                    full: function (elem) {
                        var win = window.top === window.self ? window : parent.window;
                        $(win).on('resize', function () {
                            debugger;
                            var $this = $(this);
                            elem.width($this.width()).height($this.height()).css({
                                top: 0,
                                left: 0
                            });
                            elem.children('div.layui-layer-content').height($this.height() - 95);
                        });
                    },
                    success: function (layero, index) {
                        var form = layui.form;
                        $.ajax({
                            type: "GET",
                            url: "/menu/authorityTree",
                            success: function (defaultData) {
                                authorityElement.init();
                                var $checkableTree = $('#menuTreeview').treeview({
                                    data: defaultData,
                                    levels: 1,
                                    showIcon: false,
                                    showCheckbox: true,
                                    multiSelect: false,
                                    levels: 5,
                                    state: {
                                        checked: true,
                                        disabled: true,
                                        expanded: true,
                                        selected: true
                                    },
                                    onNodeUnchecked: function (event, data) {
                                        var selectNodes = treeViewHelper.getChildrenNodeIdArr(data);//获取所有子节点
                                        if (selectNodes) { //子节点不为空，则选中所有子节点
                                            $('#menuTreeview').treeview('uncheckNode', [selectNodes, {silent: true}]);
                                        }
                                    },
                                    onNodeChecked: function (event, data) {
                                        group.currentAuthorityMenu = data;
                                        var selectNodes = treeViewHelper.getChildrenNodeIdArr(data);//获取所有子节点
                                        if (selectNodes) {
                                            $('#menuTreeview').treeview('checkNode', [selectNodes, {silent: true}]);
                                        }
                                        var parNodes = treeViewHelper.getParentIdArr("menuTreeview", data);
                                        if (parNodes) {
                                            $('#menuTreeview').treeview('checkNode', [parNodes, {silent: true}]);

                                        }
                                    },
                                    onNodeSelected: function(event, data) {
                                        group.currentAuthorityMenu = data;                
                                        authorityElement.refresh();
                                    } ,
                                    onNodeUnselected: function(event, data) {
                                        group.currentAuthorityMenu = {};
                                        authorityElement.refresh();
                                    }
                                });
                                var findCheckableNodess = function () {
                                    return $checkableTree.treeview('search', [
                                        $('#input-check-node').val(), {
                                            ignoreCase: false,
                                            exactMatch: false
                                        }]);
                                };
                                var checkableNodes = findCheckableNodess();

                                $('#input-check-node').on('keyup', function (e) {
                                    checkableNodes = findCheckableNodess();
                                    $('.check-node')
                                        .prop('disabled', !(checkableNodes.length >= 1));
                                });
                                $.get(group.baseUrl + '/' + id + "/authority/menu", null, function (data) {
                                    if (data.code=='200') {
                                        var nodes = $('#menuTreeview').treeview('getUnselected', 0);
                                        var map = {};
                                        for (var i = 0; i < nodes.length; i++) {
                                            map[nodes[i].id] = nodes[i].nodeId;
                                            nodeMap[nodes[i].nodeId] = nodes[i];
                                        }
                                        for (var i = 0; i < data.data.length; i++) {
                                            var node = data.data[i];
                                            $('#menuTreeview').treeview('checkNode', [map[node.id], {silent: true}]);
                                        }
                                    }
                                });
                            }
                        });

                        form.on('submit(edit)', function (data) {
                            var menuList = [];
                            layero.find('#menuTreeview li').each(function(){
                                if($(this).hasClass("list-group-item node-menuTreeview node-checked")){
                                    menuList.push(nodeMap[parseInt($(this).attr('data-nodeid'))]);
                                }
                            });
                            $.ajax({
                                url: group.baseUrl + '/' + id + "/authority/menu",
                                type: 'POST',
                                data: {"menuTrees": JSON.stringify(menuList)},
                                dataType: "json",
                                success: function (data) {
                                	if(data.code=='200'){
	                                    layerTips.msg('更新成功');
	                                    layer.close(index);
	                                    // location.reload();
                                	}else{
                                		layerTips.msg(data.message);
                                		layer.close(index);
                                	}
                                }

                            });
                            //这里可以写ajax方法提交表单
                            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                        });
                    },
                    end:function(){
                        group.currentAuthorityMenu = {};
                    }
                });
                layer.full(index);
            });
        }
    });
});
